<?php

declare(strict_types=1);

namespace Service\MnGoodsService;

use App\Model\BbcModel\ClientCartTemp;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\MnGoodsClass;
use App\Model\BbcModel\MnStoreClass;
use App\Model\BbcModel\MnStoreGoods;
use App\Model\BbcModel\Mnuser;
use Hyperf\DbConnection\Db;
use PhpParser\Node\Stmt\Nop;
use Service\BaseService;
use Service\Code\Normal;
use Service\UserService\MnUserService;

use function PHPSTORM_META\map;

class MnStoreGoodsService extends BaseService
{
    /**
     * 根据终端扫码获取购物车id,将商品加入购物车
     * @param int $mnid
     * @param int $mn_sid
     * @param int $cart_id
     * @param int $cid
     * @param int $mid
     * @return array
     */
    public function getCartGoodsList(int $mnid, int $mn_sid, int $cart_id, int $cid, int $mid): array
    {
        if (empty($mid)) {
            return Normal::returnCode(Normal::ACCOUNT_UNKNOWN, '请先登录');
        }
        $checkResult = MnUserService::instance()->checkStore($mnid, $cid, $mn_sid, $mid);
        if ($checkResult['code'] != Normal::SUC) {
            return $checkResult;
        }
        $info = ClientCartTemp::instance()->info(['cart_id' => $cart_id, 'cid' => $cid]);
        if (empty($info)) {
            return Normal::returnCode(Normal::FAIL, '购物车信息不存在');
        }
        $goodsIds = json_decode($info['goods_ids'], true);
        $insertCart = [
            'mid' => $mid,
            'mnid' => 4,
            'mn_sid' => $mn_sid,
            'cid' => $cid
        ];
        //todo 业务不理解暂时不往下写了
        return [];
    }

    /**
     * 置顶，取消置顶 
     * @param int $mnid
     * @param int $goods_id
     * @param int $up
     * @param int $cid
     * @param int $mn_sid
     * @param int $mn_sid
     * @return array
     */
    public function upGoods(int $mnid, int $goods_id, int $up, int $cid, int $mn_sid, int $mid)
    {
        $checkResult = MnUserService::instance()->checkStore($mnid, $cid, $mn_sid, $mid);
        if ($checkResult['code'] != Normal::SUC) {
            return $checkResult;
        }
        $info = $checkResult['data'];
        $goodsInfo = Goods::instance()->info([
            'df' => 0,
            'status' => 1,
            'cid' => $cid
        ]);
        if (empty($goodsInfo)) {
            return Normal::returnCode(Normal::FAIL, '商品不存在或者供应商已下架');
        }
        $up = $up == 0 ? 0 : time();
        $isGoodsExist = MnStoreGoods::instance()->info(['mn_sid' => $info['id'], 'goods_id' => $goods_id, 'mid' => $mid]);
        if (empty($isGoodsExist)) {
            $result = MnStoreGoods::instance()->add([
                'mnid' => $info['mnid'],
                'mn_sid' => $info['id'],
                'goods_id' => $goods_id,
                'mid' => $mid,
                'up' => $up,
                'profit' => 0,
                'status' => 0,
                'type' => 2,
                'cd' => time(),
            ]);
        } else {
            $result = MnStoreGoods::instance()->edit(['id' => $isGoodsExist['id']], ['up' => $up]);
        }
        if ($result === false) {
            return Normal::returnCode(Normal::FAIL, '操作失败');
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }

    /**
     * 小店商品排序
     * @param int $mnid
     * @param int $goods_id
     * @param int $type
     * @param int $cid
     * @param int $mn_sid
     * @param int $mid
     * @return void
     */
    public function sortGoods(int $mnid, int $goods_id, int $type, int $cid, int $mn_sid, int $mid)
    {
        $checkResult = MnUserService::instance()->checkStore($mnid, $cid, $mn_sid, $mid);
        if ($checkResult['code'] != Normal::SUC) {
            return $checkResult;
        }
        $info = $checkResult['data'];
        $storeGoods = MnStoreGoods::instance()->info(['mn_sid' => $info['id'], 'goods_id' => $goods_id, 'mid' => $mid]);
        if (empty($storeGoods)) {
            $goods = Goods::instance()->info(['df' => 0, 'status' => 1, 'id' => $goods_id, 'cid' => $cid]);
            if (empty($goods)) {
                return Normal::returnCode(Normal::FAIL, '商品不存在或已下架');
            }
            $showOrderMax = MnStoreGoods::instance()->where('mn_sid', $info['id'])->max('show_order');
            $storeGoods = [
                'mnid' => $mnid,
                'mn_sid' => $mn_sid,
                'goods_id' => $goods['id'],
                'mid' => $mid,
                'up' => 0,
                'profit' => 0,
                'status' => 0,
                'type' => 2,
                'show_order' => $showOrderMax + 1,
                'cd' => time(),
            ];
            $storeGoods['id'] = MnStoreGoods::instance()->add($storeGoods);
        }
        if ($storeGoods['up'] > 0) {
            return Normal::returnCode(Normal::FAIL, '置顶商品按置顶时间排序');
        }
        $where = [
            ['mn_sid', '=', $info['id']],
            ['df', '=', 0],
            ['up', '=', 0]
        ];
        $where[] = ['status', '=', $storeGoods['status']];
        if ($type == 1) {
            //上移，查询排序值比他大的第一个商品 然后交换排序值
            $where[] = ['show_order', '>', $storeGoods['show_order']];
            $where['_order_'] = 'show_order asc';
        } else {
            //下移，查询排序值比他小的第一个商品 然后交换排序值
            $where[] = ['show_order', '<', $storeGoods['show_order']];
            $where['_order_'] = 'show_order desc';
        }
        $changer = MnStoreGoods::instance()->info($where);
        if (empty(($changer))) {
            if ($type == 1) {
                return Normal::returnCode(Normal::FAIL, '已经是第一位了，不能再上移了');
            } else {
                return Normal::returnCode(Normal::FAIL, '已经是最后一位了，不能再下移了');
            }
        }
        $res = MnStoreGoods::instance()->edit(['id' => $storeGoods['id']], ['show_order' => $changer['show_order']]);
        $resSecond = MnStoreGoods::instance()->edit(['id' => $storeGoods['id']], ['show_order' => $storeGoods['show_order']]);
        if ($res && $resSecond) {
            return Normal::returnCode(Normal::SUC, '操作成功');
        }
        return Normal::returnCode(Normal::FAIL, '操作失败');
    }

    /**
     * 小店分类列表
     * @param int $mnid
     * @param int $mn_sid
     * @param int $cid
     * @return array
     */
    public function classList(int $mnid, int $mn_sid, int $cid, int $mid): array
    {
        if (empty($mn_sid)) {
            if (empty($mid)) {
                return Normal::returnCode(Normal::FAIL, '请先登录');
            }
            $info = Mnuser::instance()->info(['mnid' => $mnid, 'mid' => $mid, 'status' => 1, 'pid' => $cid]);
            if (empty($info)) {
                return Normal::returnCode(Normal::FAIL, '请先开通小店');
            }
        } else {
            $info = Mnuser::instance()->info(['mnid' => $mnid, 'id' => $mn_sid, 'status' => 1, 'pid' => $cid]);
            if (empty($info)) {
                return Normal::returnCode(Normal::FAIL, '小店不存在');
            }
        }

        $list = MnStoreClass::instance()->lists(['mnid' => $mnid, 'mn_sid' => $info['id'], 'df' => 0, '_fields_' => 'id as class_id,class_name']);
        $classIds = array_column($list, 'class_id');
        $goodsNums = MnGoodsClass::instance()->whereIn('class_id', $classIds)->where('df', 0)->select([
            Db::raw('count(id) as class_count'),
            'class_id'
        ])->groupBy('class_id')->get()->toArray();
        $goodsNumMap = array_column($goodsNums, 'class_count', 'class_id');
        foreach ($list as  &$item) {
            $item['goods_num'] = $goodsNumMap[$item['class_id']] ?? 0;
            unset($item);
        }
        return Normal::returnCode(Normal::SUC, '获取成功',$list);
    }
}
